Telegram Group & Telegram Channel
Скрытые фичи Enum: как выжать максимум

Многие используют Enum как простой список констант. Но у enum.Enum в Python есть куда больше возможностей — и они могут сделать код чище и мощнее.


Вот несколько приёмов, которые мало кто использует — но зря.


1. Добавление поведения в Enum


from enum import Enum

class Status(Enum):
DRAFT = 'draft'
PUBLISHED = 'published'
ARCHIVED = 'archived'

def is_visible(self):
return self in {Status.DRAFT, Status.PUBLISHED}


Теперь Status.DRAFT.is_visible() — это просто и элегантно.


2. Enum с полями


from enum import Enum

class Color(Enum):
RED = ('#FF0000', 'danger')
GREEN = ('#00FF00', 'safe')

def __init__(self, hex_code, label):
self.hex_code = hex_code
self.label = label



Color.RED.hex_code # '#FF0000'
Color.RED.label # 'danger'



3. Автоматические значения с auto()


from enum import Enum, auto

class Role(Enum):
ADMIN = auto()
USER = auto()
GUEST = auto()


Удобно, если не важны конкретные значения, а нужны уникальные.


4. Строгая сериализация

В реальных приложениях (API, базы) лучше контролировать сериализацию enum'ов:


import json

class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Enum):
return obj.value
return super().default(obj)

json.dumps(Status.PUBLISHED, cls=CustomEncoder) # "published"



5. Сравнение по значению


Status('draft') == Status.DRAFT # True
Status('draft') is Status.DRAFT # True (enum гарантирует singleton)


Итого: Enum — это не просто константы. Это лёгкий способ инкапсулировать поведение и данные, улучшить читаемость и сделать код устойчивее к ошибкам.

👉@BookPython



tg-me.com/BookPython/3623
Create:
Last Update:

Скрытые фичи Enum: как выжать максимум

Многие используют Enum как простой список констант. Но у enum.Enum в Python есть куда больше возможностей — и они могут сделать код чище и мощнее.


Вот несколько приёмов, которые мало кто использует — но зря.


1. Добавление поведения в Enum


from enum import Enum

class Status(Enum):
DRAFT = 'draft'
PUBLISHED = 'published'
ARCHIVED = 'archived'

def is_visible(self):
return self in {Status.DRAFT, Status.PUBLISHED}


Теперь Status.DRAFT.is_visible() — это просто и элегантно.


2. Enum с полями


from enum import Enum

class Color(Enum):
RED = ('#FF0000', 'danger')
GREEN = ('#00FF00', 'safe')

def __init__(self, hex_code, label):
self.hex_code = hex_code
self.label = label



Color.RED.hex_code # '#FF0000'
Color.RED.label # 'danger'



3. Автоматические значения с auto()


from enum import Enum, auto

class Role(Enum):
ADMIN = auto()
USER = auto()
GUEST = auto()


Удобно, если не важны конкретные значения, а нужны уникальные.


4. Строгая сериализация

В реальных приложениях (API, базы) лучше контролировать сериализацию enum'ов:


import json

class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Enum):
return obj.value
return super().default(obj)

json.dumps(Status.PUBLISHED, cls=CustomEncoder) # "published"



5. Сравнение по значению


Status('draft') == Status.DRAFT # True
Status('draft') is Status.DRAFT # True (enum гарантирует singleton)


Итого: Enum — это не просто константы. Это лёгкий способ инкапсулировать поведение и данные, улучшить читаемость и сделать код устойчивее к ошибкам.

👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/BookPython/3623

View MORE
Open in Telegram


Библиотека Python разработчика | Книги по питону Telegram | DID YOU KNOW?

Date: |

That growth environment will include rising inflation and interest rates. Those upward shifts naturally accompany healthy growth periods as the demand for resources, products and services rise. Importantly, the Federal Reserve has laid out the rationale for not interfering with that natural growth transition.It's not exactly a fad, but there is a widespread willingness to pay up for a growth story. Classic fundamental analysis takes a back seat. Even negative earnings are ignored. In fact, positive earnings seem to be a limiting measure, producing the question, "Is that all you've got?" The preference is a vision of untold riches when the exciting story plays out as expected.

Telegram hopes to raise $1bn with a convertible bond private placement

The super secure UAE-based Telegram messenger service, developed by Russian-born software icon Pavel Durov, is looking to raise $1bn through a bond placement to a limited number of investors from Russia, Europe, Asia and the Middle East, the Kommersant daily reported citing unnamed sources on February 18, 2021.The issue reportedly comprises exchange bonds that could be converted into equity in the messaging service that is currently 100% owned by Durov and his brother Nikolai.Kommersant reports that the price of the conversion would be at a 10% discount to a potential IPO should it happen within five years.The minimum bond placement is said to be set at $50mn, but could be lowered to $10mn. Five-year bonds could carry an annual coupon of 7-8%.

Библиотека Python разработчика | Книги по питону from tw


Telegram Библиотека Python разработчика | Книги по питону
FROM USA